#include "stdafx.h"
#include "ffmpeg.h"
#include "ffmpeg_common_utils.h"

HRESULT process_ffmpeg_raw_packet_to_IMFSample(IMFSample** ppNewSample,AVPacket* packet,AVRational time_base,LONGLONG start_time)
{
	if (packet == NULL)
		return E_POINTER;
	HRESULT hr = S_OK;

	CComPtr<IMFSample> pSample = NULL;
	CComPtr<IMFMediaBuffer> pBuffer = NULL;

	hr = MFCreateSample(&pSample);
	if (FAILED(hr))
		return hr;

	hr = MFCreateMemoryBuffer(packet->size,&pBuffer);
	if (FAILED(hr))
		return hr;

	PBYTE pData = NULL;
	hr = pBuffer->Lock(&pData,NULL,NULL);
	if (pData == NULL)
		return hr;

	RtlCopyMemory(pData,packet->data,packet->size);
	pBuffer->Unlock();
	pBuffer->SetCurrentLength(packet->size);

	hr = pSample->AddBuffer(pBuffer);
	pSample->SetSampleTime(convert_ffmpeg_pts(packet,time_base,start_time,MF_REF_TIME_BASE));
	pSample->SetSampleDuration(packet->duration > 0 ? av_rescale(packet->duration,time_base.num * MF_REF_TIME_BASE,time_base.den):0);
	*ppNewSample = pSample;
	(*ppNewSample)->AddRef();
	return hr;
}